package com.mobi.Survey;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import org.xml.sax.SAXException;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import com.appbucks.sdk.AppBucksBanner;
import com.mobi.Survey.controller.DefaultSurveyXmlParser;
import com.mobi.Survey.controller.SurveyPojo;
import com.mobi.Survey.controller.User;
import com.mobi.Survey.model.AbstractTable;
import com.mobi.Survey.model.SurveyTable;
import com.mobi.Survey.utils.Device;
import com.mobi.Survey.utils.Helper;

/**
 * 
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * SurveyListScreen.java This class is responsible for displaying survey
 */
public class SurveyListScreen extends AbstractScreen
{
	private AppBucksBanner banner;
	private ListView lvSurveys;
	private View tvNoData;

	private CustomAdapterSurveys adapter;
	public static boolean RE_SYNCH_FROM_DB = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);

		RE_SYNCH_FROM_DB = true;
		// if there is no survey in database we will download default surveys
		// from remote server
		if (SurveyPojo.getTotalSurveys(this) == 0)
		{
			new DefaultSurveyDownloadTask().execute();
		}

		Device.getInstance().init(this);
		// Create application specific directory
		if (Device.isSdPresentForReadWrite())
			if (Helper.createDirIfNotExists(Helper.APP_FOLDER))
			{

			} else
			{
				showAlert(Messages.DIR_CREATE_ERROR);
			}
		else
		{
			showAlert(Messages.NO_SD_CARD);
		}

		// Set Header View background
		showHeaderImage(User.getInstance().getListImage());

	}

	@Override
	protected void onStart()
	{
		// TODO Auto-generated method stub
		super.onStart();
		// if (User.getInstance().isShowAds() && ADS_ENABLE)
		// {
		// AppBucksAPI.userOptOutDialog(this);
		// }
	}

	@Override
	protected void onResume()
	{

		super.onResume();

		if (User.getInstance().isShowAds()
				&& Helper.isNetworkAvailable(getBaseContext()) && ADS_ENABLE)
		{
			if (banner.getVisibility() == View.GONE)
				banner.setVisibility(View.VISIBLE);
			banner.showAd();
		}
		Helper.createDirIfNotExists(Helper.APP_FOLDER);
		// Opening database and getting surveys from sqlite db
		AbstractTable at = new SurveyTable(this);
		if (RE_SYNCH_FROM_DB)
		{
			if (at != null)
			{
				if (adapter != null)
				{
					adapter.dispose();
					adapter = null;
				}
				lvSurveys.setAdapter(null);

				adapter = new CustomAdapterSurveys(this,
						((SurveyTable) at).getSurveys(false, true, this, -1));
				if (adapter.getCount() == 0)
				{
					tvNoData.setVisibility(View.VISIBLE);
				} else
				{
					tvNoData.setVisibility(View.GONE);
				}

				lvSurveys.setAdapter(adapter);
				adapter.notifyDataSetChanged();

			}
			at.closeDB();
			RE_SYNCH_FROM_DB = false;
		}

	}

	@Override
	protected void onStop()
	{

		super.onStop();

	}

	@Override
	protected void initUiVars()
	{
		lvSurveys = (ListView) findViewById(R.id.lvSurveys);
		tvNoData = findViewById(R.id.tvNoData);
		// Added to support ads banner
		banner = (AppBucksBanner) findViewById(R.id.banner);
		// Image header added now user logins WS will return Banner image and
		// its size
		headerImage = findViewById(R.id.headerImage);
	}

	@Override
	protected int getLayoutId()
	{

		return LayoutIds.SURVEY_LIST;
	}

	@Override
	protected void onRelease()
	{
		User.getInstance().release();
		headerImage.setBackgroundDrawable(null);
	}

	public void onSurveyListClick(long surveyId)
	{
		// showShortToast("Position No " + position);

		switchScreenTo(SurveyOptionScreen.class, Long.valueOf(surveyId));
	}

	public void btnClick(View v)
	{
		// if (v.getId() == R.id.btnPullSurvey) {
		// onBtnPullSurvey();
		//
		// }
	}

	/**
	 * Download default surveys from remote location
	 * 
	 * @author Yahya Arshad
	 * 
	 */
	private class DefaultSurveyDownloadTask extends
			AsyncTask<String, Object, Object>
	{
		ProgressDialog progressDialog = null;
		private boolean gotSurvey = false;
		private String responseMsg = null;
		private List<SurveyPojo> surveys;

		protected Object doInBackground(String... params)
		{

			try
			{
				DefaultSurveyXmlParser parser = new DefaultSurveyXmlParser();
				parser.parse(getResources().getString(
						R.string.default_survey_url));
				List<SurveyPojo> defSurveys = parser.getDefaultSurveys();
				if (defSurveys != null && defSurveys.size() > 0)
				{
					SurveyPojo.commit(SurveyListScreen.this, defSurveys);
					surveys = defSurveys;
					gotSurvey = true;

					for (SurveyPojo survey : defSurveys)
					{
						String surveyIcon = survey.getIconAddress();

						int hash = Helper.getHashNameFromUrl(surveyIcon);
						String localPath = Helper.getTempFile(hash + "");
						Bitmap b = null;
						if (Helper.isFileExist(localPath))
						{
							b = Helper.decode(localPath, 1);

						}

						survey.setBitmapIcon(b);

					}

				}

			} catch (MalformedURLException e)
			{
				responseMsg = Messages.INVALID_URL;
				e.printStackTrace();
			} catch (IOException e)
			{
				responseMsg = Messages.INVALID_HOST_INTERNET_CONNECTION;
				e.printStackTrace();

			} catch (SAXException e)
			{

				e.printStackTrace();
				responseMsg = Messages.INVALID_SURVEY_XML;
			} catch (RuntimeException e)
			{
				responseMsg = e.getMessage();
			}

			return null;
		}

		protected void onPostExecute(Object result)
		{

			super.onPostExecute(result);
			progressDialog.dismiss();
			progressDialog = null;
			if (gotSurvey)
			{
				tvNoData.setVisibility(View.GONE);
				adapter = new CustomAdapterSurveys(SurveyListScreen.this,
						surveys);
				lvSurveys.setAdapter(adapter);

			} else
			{
				tvNoData.setVisibility(View.VISIBLE);
			}
			if (responseMsg != null)
				showLongToast(responseMsg);

		}

		protected void onPreExecute()
		{

			super.onPreExecute();
			try
			{
				progressDialog = ProgressDialog.show(SurveyListScreen.this, "",
						Messages.FETCHING_SURVEY);
			} catch (Exception e)
			{
				e.printStackTrace();
			}

		}

	}

	public void onBackPressed()
	{
		super.onBackPressed();

		adapter.dispose();
		adapter = null;

		lvSurveys.setAdapter(null);
		finish();

	}

}
